package com.ruoyi.module.test;

import cn.hutool.core.thread.ThreadUtil;

import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @author: xiaYZ 2024/4/11
 * @version: 1.0
 */
public class HutoolThreadDemo2 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test1();
        test2();
    }

    public static void test1() throws InterruptedException, ExecutionException {
        HuToolThreadDemo huToolThreadDemo = new HuToolThreadDemo();
        long start = System.currentTimeMillis();
        // 创建线程池
        ExecutorService executorService = ThreadUtil.newExecutor(3);
        // 线程池中执行任务
        CompletionService<List<Integer>> service = ThreadUtil.newCompletionService(executorService);
        Future<List<Integer>> future1 = service.submit(huToolThreadDemo::way1);
        Future<List<Integer>> future2 = service.submit(huToolThreadDemo::way2);
        Future<List<Integer>> future3 = service.submit(huToolThreadDemo::way3);

        // for (int i = 0; i < 3; i++) {
        //     // 获取执行结果
        //     List<Integer> integers = service.take().get();
        //     System.out.println(service.take().get());
        //
        // }
        try {
            List<Integer> integers1 = future1.get();
            List<Integer> integers2 = future2.get();
            List<Integer> integers3 = future3.get();
            System.out.println(integers1);
            System.out.println(integers2);
            System.out.println(integers3);
        }catch (Exception e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        System.out.println("总耗时：" + (System.currentTimeMillis() - start));
    }

    public static void test2() throws InterruptedException {
        long start = System.currentTimeMillis();
        HuToolThreadDemo huToolThreadDemo = new HuToolThreadDemo();
        huToolThreadDemo.way1();
        huToolThreadDemo.way2();
        huToolThreadDemo.way3();
        System.out.println("总耗时：" + (System.currentTimeMillis() - start));
    }


}
